package com.itheima.pojo.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class OssClientService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Value("${aliyun.oss.file-dir}")
    private String fileDir;

    public String uploadFile(MultipartFile file) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取文件的输入流
            InputStream inputStream = file.getInputStream();
            // 生成唯一的文件名
            String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
            // 拼接上传文件路径
            String filePath = fileDir + fileName;

            // 上传文件到OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, inputStream);
            ossClient.putObject(putObjectRequest);
            log.info("文件上传成功，文件路径：{}", filePath);

            return "https://" + bucketName + "." + endpoint + "/" + filePath; // 返回文件的访问URL
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败", e);
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }
}
